﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BitworkStudios.Scraper.Document
{
    public abstract class HtmlDocumentDefinitionBase
    {
        public static T Populate<T>(string url) where T : new()
        {
            var client = new WebScraper<T>(url);
            client.Scrape();
            return Element.GetTInstance<T>(client.DocumentStructure.Elements);
        }

        protected void Synchronise<T>(T source, T destination)
        {
            PropertyInfo[] sourceProperties = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
            PropertyInfo[] destinationProperties = destination.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);

            foreach (PropertyInfo sourceProperty in sourceProperties)
            {
                foreach (PropertyInfo destinationProperty in destinationProperties)
                {
                    if (String.CompareOrdinal(sourceProperty.Name, destinationProperty.Name) == 0)
                    {
                        try
                        {
                            destinationProperty.SetValue(destination, sourceProperty.GetValue(source));
                        }
                        catch (ArgumentException)
                        {
                            //'Get' only properties ignored
                        }
                        
                        break;
                    }
                }
            }
        }

        protected string ConditionHtml(string htmlString)
        {
            string conditionedString = htmlString.Replace("&nbsp;", "");
            conditionedString = conditionedString.Replace("\n", "");

            const RegexOptions options = RegexOptions.None;
            var regex = new Regex(@"[ ]{2,}", options);
            conditionedString = regex.Replace(conditionedString, @" ");

            return conditionedString;
        }
    }
}
